package com.ebt.m.proposal_v2.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.proposal_v2.bean.ViewLocation;
import com.ebt.m.proposal_v2.bean.ViewSize;
import com.ebt.m.proposal_v2.helper.ThemeHelper;
import com.ebt.m.proposal_v2.helper.ViewHelper;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author archer.qi
 *         Created on 2017/5/4.
 */
public class ViewUtils {


    /**
     * 这是一个PressSelector
     * Normal - 白色
     * Press - 灰色
     * 圆角
     *
     * @param context
     * @return
     */
    public static StateListDrawable createWhiteToGrayCorneredPressSelector(Context context) {
        GradientDrawable normalDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), Color.WHITE);
        GradientDrawable pressDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), ThemeHelper.getGrayBackgroundColor(context));
        return ViewHelper.generatePressSelector(normalDrawable, pressDrawable);
    }

    /**
     * 这是一个PressSelector
     * Normal - 灰色
     * Press - 深灰色
     * 圆角
     *
     * @param context
     * @return
     */
    public static StateListDrawable createGrayToDarkCorneredPressSelector(Context context) {
        GradientDrawable normalDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), Color.WHITE);
        GradientDrawable pressDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), ThemeHelper.getGrayBackgroundColor(context));
        return ViewHelper.generatePressSelector(normalDrawable, pressDrawable);
    }

    /**
     * 这是一个圆角的PressSelector
     * 至于想要什么颜色，随便你
     *
     * @param context
     * @param normalColor
     * @param pressColor
     * @return
     */
    public static StateListDrawable createCorneredPressSelector(Context context, int normalColor, int pressColor) {
        GradientDrawable normalDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), normalColor);
        GradientDrawable pressDrawable = ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), pressColor);
        return ViewHelper.generatePressSelector(normalDrawable, pressDrawable);
    }

    /**
     * 这是一个圆角的指定填充色的Drawable
     *
     * @param context
     * @param color
     * @return
     */
    public static GradientDrawable createCornerDrawable(Context context, int color) {
        return ViewHelper.genetateCornerGradientDrawable(
                ThemeHelper.getBackgroundCornerRadius(context), color);
    }

    /**
     * 这是一个指定圆角与边框色的Drawable
     *
     * @param cornerRadius
     * @param strokeColor
     * @return
     */
    public static GradientDrawable createCorneredStrokedDrawable(float cornerRadius, int solidColor, int strokeColor) {
        return ViewHelper.genetateCornerStrokedGradientDrawable(cornerRadius, solidColor, strokeColor);
    }

    /**
     * 设置背景
     *
     * @param view
     * @param background
     */
    public static void setBackgroundDrawable(View view, Drawable background) {
        if (view == null || background == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(background);
        } else {
            view.setBackgroundDrawable(background);
        }
    }

    /**
     * 映射View
     *
     * @param context
     * @param layoutId
     * @return
     */
    public static View inflate(Context context, int layoutId) {
        return ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(layoutId, null);
    }

    /**
     * WebView提示窗口
     *
     * @param activity
     * @param title
     * @param message
     * @param positive
     * @param negative
     * @param result
     */
    public void showWebViewChromeDialog(
            Activity activity, String title, String message, String positive, String negative, JsResult result) {
        if (ActivityUtils.isActivityActive(activity)) {
            // Activity没有被回收或结束
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(title);
            builder.setMessage(message);
            if (positive != null) {
                builder.setPositiveButton(positive, (dialog, which) -> {
                    if (result != null) {
                        result.confirm();
                    }
                });
            }
            if (negative != null) {
                builder.setNegativeButton(negative, (dialog, which) -> {
                    if (result != null) {
                        result.cancel();
                    }
                });
            }
            builder.setCancelable(false);
            builder.create();
            builder.show();
        }
    }

    /**
     * 测量View尺寸
     *
     * @param view
     * @return
     */
    public static ViewSize measureView(View view) {
        if (view == null) {
            return null;
        }
        view.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED));
        return new ViewSize(view.getMeasuredWidth(), view.getMeasuredHeight());
    }

    /**
     * 定位View
     *
     * @param view
     * @return
     */
    public static ViewLocation locateView(View view) {
        if (view == null) {
            return null;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return new ViewLocation(location[0], location[1]);
    }

    public static void setEBTWebView(WebView webView) {
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setHorizontalScrollBarEnabled(false);
        webView.requestFocus();
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setDatabaseEnabled(false);
        webView.getSettings().setDomStorageEnabled(false);
        webView.getSettings().setAppCacheEnabled(false);

        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
        webView.getSettings().setJavaScriptEnabled(true);
//        webView.getSettings().setDomStorageEnabled(true);
        webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setTextZoom(100);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && (url.startsWith("http") || url.startsWith("https"))) {
                    webView.postDelayed(() -> webView.loadUrl(processUrl(url)), 100);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//接受证书
            }
        });
    }

    public static String processUrl(String url) {
        if (url.contains("wifi") && url.contains("url=")) {
            int urlstartIndex = url.indexOf("url=") + 4;
            url = url.substring(urlstartIndex);
            int urlendIndex = url.length();
            if (url.contains("&")) {
                urlendIndex = url.indexOf("&");
            }
            url = url.substring(0, urlendIndex);
            try {
                url = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }
        }
        return url;
    }

    public static void toWeb(Context context, String title, String url) {
        Bundle bundle = new Bundle();
        bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, title);
        bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4OLD_BASE);
        bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, false);
        bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, 5);

        bundle.putString(WebBaseActivity.WEB_TYPE_LINK, url);
        Intent intent = new Intent(context, WebBaseActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static float screenDensity(Context context) {
        DisplayMetrics outMetrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.density;
    }

    public static int parseColor(String color, int defaultColor) {
        if (TextUtils.isEmpty(color)) {
            return defaultColor;
        }
        try {
            return Color.parseColor(color);
        } catch (Exception ex) {
            return defaultColor;
        }
    }
}
